﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.EventBus.Distributed;

namespace Ordering.Orders
{
    public class OrderAppService : OrderingAppService, IOrderAppService
    {
        private readonly IRepository<Order, int> _repository;
        private readonly IDistributedEventBus _distributedEventBus;

        public OrderAppService(
            IRepository<Order, int> repository,
            IDistributedEventBus distributedEventBus)
        {
            _repository = repository;
            _distributedEventBus = distributedEventBus;
        }

        public async Task CreateAsync(string name)
        {
            Console.WriteLine($"开始创建Order_{DateTime.Now}");
            var order = await _repository.InsertAsync(new Order()
            {
                Name = name
            });
            Console.WriteLine($"完成创建Order_{DateTime.Now}");

            Console.WriteLine($"开始发送集成事件_{DateTime.Now}");
            await _distributedEventBus.PublishAsync(new OrderCreatedEto
            {
                Id = order.Id,
                Name = order.Name
            });
            Console.WriteLine($"完成发送集成事件_{DateTime.Now}");

            //for (int i = 0; i < 10; i++)
            //{
            //    Thread.Sleep(1000);
            //    System.Console.WriteLine($"模拟其他事情{i}_{DateTime.Now}");
            //}

            //Console.WriteLine($"模拟抛出异常_{DateTime.Now}");
            //throw new System.Exception("error");
        }
    }
}